package com.midcent.networklib.interfac;
import android.os.Environment;
import android.util.Log;

import com.android.volley.Cache;
import com.android.volley.toolbox.DiskLruBasedCache;

import java.io.File;

/**
 * Created by kexiang on 16/8/12.
 */
public class LRUCacheManager {
    private static DiskLruBasedCache cache;
    private final static String rootdir = Environment.getExternalStorageDirectory()+"/voll";
    private static LRUCacheManager instance;
    private static long EXPIR = 1000 * 3600 * 72;

    private LRUCacheManager() {
        File dir = new File(rootdir);
        if(!dir.exists()){
            dir.mkdirs();
        }
        cache = new DiskLruBasedCache(dir);
        cache.initialize();
    }

    public static LRUCacheManager getInstance() {
        if (instance == null) {
            instance = new LRUCacheManager();
        }
        return instance;
    }

    public DiskLruBasedCache getDiskCache() {
        return cache;
    }

    public void put(String url, String para, String response) {
        String key = url + para;
        if (response == null) {
            return;
        }
        Cache.Entry entry = new Cache.Entry();

        byte[] data = response.getBytes();
        entry.data = data;
        entry.softTtl = System.currentTimeMillis() + EXPIR;
        cache.put(key, entry);
    }

    public String get(String url, String para) {
        Cache.Entry entry = cache.get(url + para);
        if (entry != null) {
            return new String(entry.data);
        }
        return null;
    }
}
